package com.gjszn.kh.controller.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.gjszn.kh.context.MemberContext;
import com.gjszn.kh.context.SysContext;
import com.gjszn.kh.mail.MailSenderUtil;
import com.gjszn.kh.model.AdminPO;
import com.gjszn.kh.model.HtmlMailBean;
import com.gjszn.kh.model.Member;
import com.gjszn.kh.model.User;
import com.gjszn.kh.model.UserVO;
import com.gjszn.kh.service.RecommendationCodeSerivce;
import com.gjszn.kh.service.UserService;
import com.gjszn.kh.utils.DateUtil;
import com.gjszn.kh.utils.FreemarkerUtil;
import com.gjszn.kh.utils.PdfHelper;
import com.gjszn.kh.utils.PdfUtils;


/**    
* @Title: UserController.java  
* @Package com.gjszn.kh.controller.admin    
* @author jys@nx-yt.com    
* @date 2016年1月5日 下午3:46:10  
* @version V1.0    
* @Description: TODO(用一句话描述该文件做什么)
********************************************/
@Controller
@RequestMapping("/admin/users")
public class UserController {
	private static Logger log = LogManager.getRootLogger();
	@Inject
	private UserService userService;
	
	@Inject
	private MailSenderUtil mailSenderUtil;
	
	@Inject
	private RecommendationCodeSerivce recommendationCodeSerivce;
	
	@RequestMapping("")
	public String toUsersView(HttpSession session){
		AdminPO adminPO = (AdminPO) session.getAttribute(SysContext.SYS_ADMIN);
		if(adminPO == null){
			return null;
		}
		String member = "admin".equals(adminPO.getNickname()) ? null : adminPO.getNickname();
		session.setAttribute("q_codes", recommendationCodeSerivce.getAllByMember(member));
		return "admin/users";
	}
	
	/**
	 * 根据分页信息查询数据
	 * @param page
	 * @param rows
	 * @param session
	 * @return JSONObject
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value="load", method=RequestMethod.POST)
	public @ResponseBody JSONObject load(int page, int rows, HttpSession session) throws IllegalAccessException, InvocationTargetException{
		AdminPO adminPO = (AdminPO) session.getAttribute(SysContext.SYS_ADMIN);
		if(adminPO == null){
			return null;
		}
		String member = "admin".equals(adminPO.getNickname()) ? null : adminPO.getNickname();
		log.info("member:" + member);
		List<UserVO> users = userService.list(member, "u.id", false, page, rows);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", userService.total(member));
		jsonObject.put("rows", users);
		return jsonObject;
	}
	
	/**
	 * 根据查询添加进行分页查询数据
	 * @param name
	 * @param number
	 * @param status
	 * @param startTime
	 * @param endTime
	 * @param page
	 * @param rows
	 * @param session
	 * @return JSONObject
	 */
	@RequestMapping(value="query", method=RequestMethod.POST)
	public @ResponseBody JSONObject query(String member, 
			String name, 
			String number, 
			String code, 
			int status, 
			String startDate, 
			String endDate, int page, int rows, HttpSession session){
		AdminPO adminPO = (AdminPO) session.getAttribute(SysContext.SYS_ADMIN);
		if(adminPO == null){
			return null;
		}
		String _member = null;
		if("admin".equals(adminPO.getNickname())){
			_member = ("-1".equals(member) || "".equals(member) || member==null || MemberContext.getByKey(member)==null) ? null : member;
		}else{
			_member = adminPO.getNickname();
		}
		log.info(_member + "会员单位进行查询数据");
		Integer _status = (status >= 0) ? status : null;
		String _code = ("-1".equals(code) || "".equals(code) || code==null) ? null : code;
		String _name = ("".equals(name) || name==null) ? null : name;
		String _number = ("".equals(number) || number==null) ? null : number;
		String _startDate = null;
		if("".equals(startDate) || startDate==null){
			_startDate = "2016-01-01 00:00:00";
		}else{
			_startDate = startDate;
		}
		String _endDate = null;
		if("".equals(startDate) || startDate==null){
			_endDate = DateUtil.getNowDateTime();
		}else{
			_endDate = endDate;
		}
		List<UserVO> users = userService.queryData(_name, _number,_code,  _startDate, _endDate, _status, _member, "u.id", true, page, rows);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", userService.queryDataTotal(_name, _number, _code, _startDate, _endDate, _status, _member));
		jsonObject.put("rows", users);
		return jsonObject;
	}
	
	
	/**
	 * 会员审核通过，开出交易账号，请求交易中心进行审核
	 * @param id
	 * @param number
	 * @return JSONObject
	 */
	@RequestMapping(value="number/create", method=RequestMethod.POST)
	public @ResponseBody  JSONObject createNumber(int id, String number){
		log.info("id:" + id + ", number:" + number);
		JSONObject jsonObject = new JSONObject();
		if(userService.updateCreateNumber(id, number)){
			jsonObject.put("status", 1);
			jsonObject.put("msg", "信息已经提交给交易中心");
		}else{
			jsonObject.put("status", -1);
			jsonObject.put("msg", "信息处理失败");
		}
		return jsonObject;
	}
	
	/**
	 * 客户已入金，请求交易中心激活
	 * @param id
	 * @param amount
	 * @return JSONObject
	 */
	public JSONObject inMoney(int id, String amount){
		return null;
	}
	
	/**
	 * 交易中心对交易账户进行激活，并发送短信或邮件通知会员和客户
	 * @param id
	 * @return JSONObject
	 */
	@RequestMapping(value="number/active", method=RequestMethod.POST)
	public @ResponseBody JSONObject activeNumber(int id){
		JSONObject jsonObject = new JSONObject();
		if(userService.updateActiveNumber(id)){
			jsonObject.put("status", 1);
			jsonObject.put("msg", "已经标示为已激活");
		}else{
			jsonObject.put("status", -1);
			jsonObject.put("msg", "信息处理失败");
		}
		return jsonObject;
	}
	
	/**
	 * 审核通过发送邮件通知
	 * @param id
	 * @param name
	 * @param sex
	 * @param phone
	 * @param email
	 * @param request
	 * @return JSONObject
	 */
	@RequestMapping(value="approve", method=RequestMethod.POST)
	public @ResponseBody JSONObject approve(int id, HttpServletRequest request){
		JSONObject jsonObject = new JSONObject();
		String baseUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ request.getContextPath();
		if(userService.updateApproveNumber(id, baseUrl)){
			jsonObject.put("status", 1);
			jsonObject.put("msg", "激活邮件已经发出");
			return jsonObject;
		}
		jsonObject.put("status", -1);
		jsonObject.put("msg", "发送邮件出错！");
		return jsonObject;
	}
	
	/**
	 * 给客户发送短信或邮件，告知审核结果
	 * @param id 客户id
	 * @param context 消息内容
	 * @return JSONObject
	 */
	@RequestMapping(value="send/msg", method=RequestMethod.POST)
	public @ResponseBody JSONObject sendMsg(int id, String member, String number, String name, String sex, String phone, String email, String content, HttpSession session){
		AdminPO adminPO = (AdminPO) session.getAttribute(SysContext.SYS_ADMIN);
		if(adminPO == null){
			return null;
		}
		log.info("sendMsg-----id:" + id + ", context:" + content);
		JSONObject jsonObject = new JSONObject();
		// 1、发送消息通知客户
		log.info("1、已经发送消息给客户");
		if(email == null || "".equals(email)){
			jsonObject.put("status", -1);
			jsonObject.put("msg", "客户邮箱不正确, 不能发送邮件通知");
			return jsonObject;
		}
		try {
			HtmlMailBean mailBeans = new HtmlMailBean();
			mailBeans.setSubject(mailSenderUtil.getSubjectMark() + name + "--资料未通过审核");
			mailBeans.setTo(email);
			Map<String, Object> rootData = new HashMap<String, Object>();
			rootData.put("name", name);
			rootData.put("number", number);
			rootData.put("sex", "男".equals(sex)? 1 : 0);
			rootData.put("memberNo", MemberContext.getByKey(member).getNumber());
			rootData.put("memberName", MemberContext.getByKey(member).getName());
			rootData.put("content", content);
			String mailContent = FreemarkerUtil.getFreemarkViewString("mail_error.ftl", rootData);
			mailBeans.setContent(mailContent);
			mailSenderUtil.sendMail(mailBeans);
			jsonObject.put("status", 1);
			jsonObject.put("msg", "已经发送消息给客户");
		} catch (Exception e) {
			jsonObject.put("status", 0);
			jsonObject.put("msg", "服务器出错，请稍后再试");
			log.warn(e.getMessage());
		}
		// 2、如果是交易中心选择发送消息，则要发送消息通知客户所属的会员单位
		//if("admin".equals(adminPO.getNickname())){
			//log.info("2、如果是交易中心选择发送消息，则要发送消息通知客户所属的会员单位");
		//}
		return jsonObject;
	}
	
	/**
	 * 删除一个客户信息，让其重新注册
	 * 此处为假删除，只是为此客户标记为deleted=1
	 * @param id
	 * @return JSONObject
	 */
	@RequestMapping(value="delete", method=RequestMethod.POST)
	public @ResponseBody JSONObject delete(int id, HttpSession session){
		AdminPO adminPO = (AdminPO) session.getAttribute(SysContext.SYS_ADMIN);
		if(adminPO == null){
			return null;
		}
		String member = "admin".equals(adminPO.getNickname()) ? null : adminPO.getNickname();
		JSONObject jsonObject = new JSONObject();
		if(userService.delete(id, member)){
			jsonObject.put("status", 1);
			jsonObject.put("msg", "数据已删除");
		}else{
			jsonObject.put("status", -1);
			jsonObject.put("msg", "信息处理失败");
		}
		return jsonObject;
	}
	
	/**
	 * 下载pdf的客户协议书
	 * @param id
	 * @param response void
	 * @throws IOException 
	 */
	@RequestMapping(value="down/pdf")
	public void downPDF(int id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = userService.getById(id);
		if(user == null){
			log.info("用户不存在，无法生产客户协议书");
			return;
		}
		AdminPO adminPO = (AdminPO) request.getSession().getAttribute(SysContext.SYS_ADMIN);
		log.info("admin:" + adminPO.getNickname());
		OutputStream out = null;
		try {
			Map<String, String> data = new HashMap<String, String>();
			Member memberBean = MemberContext.getByKey(user.getMember());
			data.put("hydw", memberBean.getName());
			data.put("mphone", memberBean.getPhone());
			data.put("name", user.getName());
			data.put("phone", user.getPhone());
			String path = PdfHelper.getPath("ftl/pdf");
			response.setContentType("application/x-download");
			String fileName = URLEncoder.encode(user.getName(), "UTF-8");
			response.setHeader("Content-Disposition",
					"attachmeng;filename=" + fileName + "khxys.pdf");
			out = PdfUtils.generateToServletOutputStream(path, "khxys.html", null, data, response);
			log.info("[" + user.getName() + "]客户协议书生成成功！");
			out.flush();
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	
}

